;; Emacs 的 auto-save-mode 会产生大量 #*# 文件，因此自定义了这个功能
;; 代码来自网络，经过修改

(setq auto-save-default nil)            ;关闭 Emacs 自带的自动保存

(defgroup my/autosave nil
  "Auto save file when emacs idle."
  :group 'my/autosave)

(defcustom my/autosave-idle 5
  "设置自动保存的等待时间，单位秒"
  :type 'integer
  :group 'my/autosave)

(defcustom my/autosave-slient nil
  "如果设置为 nil 则自动保存时会在 minibuf 显示提示，设置为 t 则不显示"
  :type 'boolean
  :group 'my/autosave)

(defun my/autosave-current-buffer ()
  "保存当前 Buffer，如果已修改"
  (interactive)
  (if (and (buffer-file-name) (buffer-modified-p))
      (progn
        (if my/autosave-slient
            (with-temp-message "" (basic-save-buffer))
          (basic-save-buffer))
        (buffer-name (current-buffer)))
    nil))

(defun my/autosave-all-buffer ()
  "保存所有已修改的 Buffer"
  (interactive)
  (let ((autosave-buffer-list '())
        (name))
    (save-excursion
      (dolist (buf (buffer-list))
        (set-buffer buf)                ;将需要保存的Buffer设置为当前Buffer
        (when (my/autosave-current-buffer)
          (push (buffer-name buf) autosave-buffer-list))
        ))

      (unless my/autosave-slient
        (cond
         ((= (length autosave-buffer-list) 1)
          (message "Saved file: %s" (elt autosave-buffer-list 0)))
         ((> (length autosave-buffer-list) 1)
          (message "Saved %d files: %s"
                   (length autosave-buffer-list)
                   (mapconcat 'identity autosave-buffer-list ", ")))))
      ))

(defun my/autosave-current-buffer-enable ()
  (interactive)
  (run-with-idle-timer my/autosave-idle t #'my/autosave-current-buffer))

(defun my/autosave-all-buffer-enable ()
  (interactive)
  (run-with-idle-timer my/autosave-idle t #'my/autosave-all-buffer))


;; 开启自动保存
(my/autosave-all-buffer-enable)

(provide 'my/auto-save)
